'''
Created on Jul 2, 2011

@author: pau <boemianrapsodi@gmail.com>
'''

from Utils.RepoFoldersManager import RepoFoldersManager;
from Utils.Server import Server;
from Utils.ConfigurationController import ConfigurationController;
import sys, time, threading;

class LocalMarketServer:
    "Server main class"
    configuration=None;
    treeManager=None;
    sessionServer=None;
    
    running=True;
    commandReceived=None;
    
    def __init__ (self):
        self.configuration = ConfigurationController(); 
        self.treeManager = RepoFoldersManager(self.configuration.GetPacketsDir());
        self.sessionServer = Server(self.configuration.GetServerAddress(), int(self.configuration.GetServerPort()));
        while self.running:
            print "In listening";
            #threading.Thread(target=self.DrawSpinner).start();
            self.commandReceived=self.sessionServer.ReceiveCommand();
            if self.commandReceived[0]=="CMD:close":
                self.CloseServer();
            elif self.commandReceived[0]=="CMD:srvInfo":
                self.commandReceived[1][1]+=1;
                self.sessionServer.Respond(self.configuration.GetServerName(), self.commandReceived[1]);
            elif self.commandReceived[0]=="CMD:getList":
                threading.Thread(target=self.sessionServer.SendAFile,args=(self.commandReceived[1][0], self.treeManager.GetPacketsFolder()+"/packetsList.xml")).start();
            self.commandReceived = None;
            
    
    def DrawSpinner(self,delay=0.2):
        spinner = ('/', '-', '\\', '|');
        index=0;
        while self.commandReceived==None:
            sys.stdout.write(spinner[index]);
            sys.stdout.flush();
            time.sleep(delay);
            sys.stdout.write('\r');
            index = index<3 and index+1 or 0;

    
    
    def CloseServer(self):
        print "Closing Server";
        self.running=False;
        exit();
         


if __name__ == "__main__":
    LocalMarketServer();